package com.hewep.demo.device.mina.core;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class ActionMapping {
	private static final String SLASH = "/";
	private Routes routes;
	
	private final Map<String, Action> mapping = new HashMap<String, Action>();
	
	private static final Logger log = LoggerFactory.getLogger(ActionMapping.class);
	
	public ActionMapping(Routes routes) {
		this.routes = routes;	
		this.buildActionMapping();
	}
		
	
	public void buildActionMapping() {
		mapping.clear();
		log.info("开始构建命令与业务类映射关系");		
		for (Entry<String, Class<? extends Controller>> entry : routes.getEntrySet()) {
			Class<? extends Controller> controllerClass = entry.getValue();	
			try{
				//Method method = controllerClass.getMethod("action");
				String controllerKey = entry.getKey();
				if (mapping.containsKey(controllerKey)) {
					log.warn("重复映射的业务处理类{}",controllerClass.getName());
					continue;
				}
				Method[] methods = controllerClass.getDeclaredMethods();
				for (Method method : methods) {
					String actionKey = controllerKey+SLASH+method.getName();
					Action action = new Action(actionKey, controllerClass,method, method.getName());
					mapping.put(actionKey, action);	
				}
				
			}catch(Exception e){
				log.warn("初始化业务类{}发生错误：{}",controllerClass.getName(),e.getMessage());
			}			
		}
		log.info("构建业务处理映射成功: {}",mapping.toString());
	}	
	
	public Action getAction(String method) {
		Action action = mapping.get(method);
		if (action != null) {
			return action;
		}else{
			return mapping.get(method+SLASH+"action");		
		}
		
	}
	
	List<String> getAllActionKeys() {
		List<String> allActionKeys = new ArrayList<String>(mapping.keySet());
		Collections.sort(allActionKeys);
		return allActionKeys;
	}
	
}
